package com.linght.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.linght.captcha.model.CpatchaModel;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Description:  验证码生成
 * User:岁亮亮
 * Date:2024-11-11
 * TIME:16:01
 */

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CpatchaModel cpatchaModel;
    //设置验证码的保质期 60s
    private static final long captcha_valid_timeDate = 60*1000;
    //1 后端生成验证码 借助hutool工具
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        //验证码图片的设置和生成
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cpatchaModel.getWidth(),cpatchaModel.getHeight());
        try{
            //设置返回类型
            response.setContentType("image/jpeg");
            //禁止缓存
            response.setHeader("Pragma", "No-cache");
            //将验证码写出到流 用response 对象调用getOutputStream写出
            lineCaptcha.write(response.getOutputStream());
            //将后端生成的验证码保存在session ,每一个用户都有一个session对象
            // 他是根据HttpServletRequset对象的getCookies()得到sessionId进而获取到session对象的
            session.setAttribute("captcha_session_key", lineCaptcha.getCode());
            //设置生产日期 检查验证码是否失效
            session.setAttribute("captcha_session_ProductionDdate",new Date());
            response.getOutputStream().flush();
        }catch (RuntimeException e){
            throw new RuntimeException();

        }
    }
    @RequestMapping("/verfity")
    public Boolean verfity(String inputCode,HttpSession session){
        //首先将传过来的inputCode 进行判空
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }
        //获取验证码
        String code = (String) session.getAttribute(cpatchaModel.getSession().getKey());
        Date date = (Date) session.getAttribute(cpatchaModel.getSession().getDate());
        if(inputCode.equalsIgnoreCase(code)){
            if(code != null && System.currentTimeMillis() - date.getTime() < captcha_valid_timeDate){
                return true;
            }
        }
        return false;


    }
































}
